﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Tool
{
    /// <summary>
    /// ef扩展类
    /// </summary>
    public static class EFExtensionMethod
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="totalPage"></param>
        /// <returns></returns>
        public static List<T> GetByPage<T>(this IQueryable<T> source, int pageIndex, int pageSize, out int totalCount, out int totalPage)
        {
            totalCount = source.Count();
            totalPage = Convert.ToInt32(Math.Ceiling(totalCount * 1.0 / pageSize));
            return source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 条件满足则添加条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="where"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static IQueryable WhereIf<T>(this IQueryable<T> source, bool where, Expression<Func<T, bool>> predicate)
        {
            if (where)
            {
                source = source.Where(predicate);
            }

            return source;
        }
    }
}
